<template>
  <div class="mar-tb-20px">
    <div class="btn-group w-full pd-tb-10-px btn-pos">
      <el-button @click="buildPrompt" size="small">预览提示词</el-button>
<!--      <el-button @click="allFanyi" size="small" :disabled="isLoad">-->
<!--        <i class="el-icon-loading" v-if="isLoad"></i><span>翻译所有提示词</span>-->
<!--      </el-button>-->
      <el-button @click="setConfig" size="small">配置</el-button>
    </div>
    <el-table
        :data="data"
        border
        style="width: 100%">
      <el-table-column
          type="index">
      </el-table-column>
      <el-table-column
          prop="text"
          label="原文"
          width="480">
        <template   v-slot:header="scope">
          <span>原文</span>
          <el-button type="text" @click.native="toTsc()"> >>提示词 </el-button>
        </template>
        <template v-slot:default="{row,$index}">
          <el-input type="textarea" v-model="row.text" :autosize="{ minRows: 2}"></el-input>
        </template>
      </el-table-column>
      <el-table-column
          prop="storyboard"
          label="镜头">
        <template v-slot:default="{row,$index}">
          <el-input type="textarea" v-model="row.storyboard" :autosize="{ minRows: 2}"></el-input>
        </template>
      </el-table-column>
      <el-table-column
          prop="storyboard"
          label="英文提示词">
        <template v-slot:default="{row,$index}">
          <el-input type="textarea" v-model="row.storyboarden" :autosize="{ minRows: 2}" @change="textChange(row,$index)"></el-input>
        </template>
      </el-table-column>
      <el-table-column
          prop="action"
          width="100"
          label="操作">
        <template v-slot:default="{row,$index}">
          <el-dropdown trigger="click" class="pointer">
            <span class="el-dropdown-link "> <i class="el-icon-s-operation el-icon--right font-20px"></i> </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item icon="el-icon-top" v-if="$index !== 0" @click.native="upMerge($index,row , )">向上合并</el-dropdown-item>
              <el-dropdown-item icon="el-icon-bottom" v-if="$index !== data.length -1" @click.native="downMerge($index,row )">向下合并</el-dropdown-item>
              <el-dropdown-item icon="el-icon-delete" @click.native="deleteRow($index , false)">删除</el-dropdown-item>
              <el-dropdown-item icon="el-icon-delete" v-if="$index !== 0" @click.native="deleteRow($index,true ,'up')">删除 <i class="el-icon-top"></i></el-dropdown-item>
              <el-dropdown-item icon="el-icon-delete" v-if="$index !== data.length -1" @click.native="deleteRow($index,true ,'down')">删除 <i class="el-icon-bottom"></i></el-dropdown-item>
              <el-dropdown-item icon="el-icon-plus" @click.native="insertRow($index)">插入一行</el-dropdown-item>
<!--              <el-dropdown-item icon="el-icon-circle-check" @click.native="rowFy(row,$index)">翻译</el-dropdown-item>-->
              <el-dropdown-item icon="el-icon-copy-document" @click.native="copyPrompt(row,$index)">复制提示词</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <i class="el-icon-loading font-20px" v-if="row.isLoad"></i>
        </template>
      </el-table-column>
    </el-table>
    <prompt-box :prompt="storyboardzh" :promptEn="storyboarden" v-model="pStatus"></prompt-box>
    <el-drawer
        title="配置"
        :visible.sync="dialog"
        direction="ltr"
        size="70%"
        custom-class="pd-20px"
        ref="drawer"
    >
      <div class="demo-drawer__content">
        <el-form :model="config">
          <el-form-item label="AI token" :label-width="formLabelWidth">
            <el-input   v-model="config.token"  ></el-input>
          </el-form-item>
          <el-form-item label="GPT模型" :label-width="formLabelWidth">
            <v2-select v-model="config.model" :config="{
              options:[
                  {
                    label: 'gpt-3.5-turbo',
                    value: 'gpt-3.5-turbo'
                  },
              ]
            }"></v2-select>
          </el-form-item>
          <el-form-item label="AI指导角色" :label-width="formLabelWidth">
            <el-input type="textarea" v-model="config.systemContent" :autosize="{ minRows: 2}"></el-input>
          </el-form-item>
          <el-form-item label="正向默认提示词" :label-width="formLabelWidth">
            <el-input type="textarea" v-model="config.prompt" :autosize="{ minRows: 2}"></el-input>
          </el-form-item>
          <el-form-item label="反向向默认提示词" :label-width="formLabelWidth">
            <el-input type="textarea" v-model="config.negativePrompt" :autosize="{ minRows: 2}"></el-input>
          </el-form-item>
          <el-form-item label="采样步数" :label-width="formLabelWidth">
            <el-input-number   v-model="config.steps"  ></el-input-number>
          </el-form-item>
          <el-form-item label="随机种子" :label-width="formLabelWidth">
            <el-input-number   v-model="config.seed"  ></el-input-number>
          </el-form-item>
          <el-form-item label="提示词引导系数" :label-width="formLabelWidth">
            <el-input-number   v-model="config.cfgScale"  ></el-input-number>
          </el-form-item>

          <el-form-item label="宽高比例" :label-width="formLabelWidth">
            <v2-select v-model="config.size" :config="{
              options:[
                  {
                    label: '16:9',
                    value: '1024x576'
                  },
                  {
                    label: '9:16',
                    value: '576x1024'
                  }
              ]
            }"></v2-select>
          </el-form-item>
          <el-form-item label="采样器" :label-width="formLabelWidth">
            <v2-select v-model="config.sampler" :config="{
              options:[
                  {
                    label: 'DPM++ 2M Karras',
                    value: 'DPM++ 2M Karras'
                  },
                  {
                    label: 'DPM++ 2S a Karras',
                    value: 'DPM++ 2S a Karras'
                  },
                  {
                    label: 'DPM++ SDE Karras',
                    value: 'DPM++ SDE Karras'
                  },
                  {
                    label: 'DPM++ 2M SDE Karras',
                    value: 'DPM++ 2M SDE Karras'
                  }
              ]
            }"></v2-select>
          </el-form-item>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button @click="dialog = false" size="small">取 消</el-button>
          <el-button type="primary" @click="saveConfig" size="small">保存</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import commons from "utils/commons";
import util from "utils/util";
import PromptBox from "views/tw/promptBox";
import http from "network/http";

export default {
  name: "V2List" ,
  components: {PromptBox},
  props:{
    dataList: Array,
  },
  data(){
    return {
      data: [] ,
      dialog: false ,
      formLabelWidth: "140px" ,
      defaultPrompt: "((masterpiece)), ((best quality)), 8k, high detailed, ultra-detailed" ,
      storyboardzh: "" ,
      storyboarden: "" ,
      pStatus: false ,
      isLoad: false ,
      defConfig: {
        negativePrompt: "NSFW ,low quality,lowres,low resolution, noise ,monochorome, grayscale ,missing part, bad proportions, ugly , extra hands,extra fingers,missing hands" ,
        prompt: "((masterpiece)), ((best quality)), 8k, high detailed, ultra-detailed" ,
        sampler: "DPM++ 2M Karras" ,
        steps: 30 ,
        Seed: -1,
        size: "1024x576",
        cfgScale: 7 ,
        clipSkip: '2',
        token: "",
        model: 'gpt-3.5-turbo',
        systemContent: ''
      }
    }
  },
  computed:{
    config(){
      return JSON.parse(localStorage.getItem("prompt_config")) || this.defConfig;
    }
  },

  methods:{
    textChange(row,index){
     let text = row.storyboarden ;
     row.storyboarden = text.split("\n").filter(item=>!util.isVoid(item)).join(",")
    },
    saveConfig(){
      this.$refs.drawer.closeDrawer() ;
      localStorage.setItem("prompt_config",JSON.stringify(this.config))
      this.$message.success("保存成功")
    },
    setConfig(){
        this.dialog = true ;
        let config = localStorage.getItem("prompt_config") ;
        if(config){
          this.config = JSON.parse(config)
        }
    },
    allFanyi(){
      let p = []
      this.data.forEach((item,index)=>{
        if(!util.isVoid(item.storyboard)){
          p.push(this.fyRequest(item,index))
        }
      })
      if(p.length >0) {
        this.isLoad = true
        Promise.all(p).then(res=>{
          res.forEach(item=>{
            if(item.success === true){
              let index = item.api_config.index ;
              this.data[index].storyboarden = item.translated_text.toString()
            }
          })

        }).finally(()=>{
          this.isLoad = false
        })
      }
    },
    copyPrompt(row){
      let c = this.config ;
      let text = `${c.prompt},${row.storyboarden}
       Negative prompt: ${c.negativePrompt}
       Steps: ${c.steps} , Sampler: ${c.sampler}, CFG scale: ${c.cfgScale} ,Seed:${c.seed}, Size:${c.size}, Denoising strength: 0.45,Clip skip: 2 , Hires upscale: 2, Hires steps: 15, Hires upscaler: R-ESRGAN 4x+ Anime6B,
       `
      try {
        navigator.clipboard.writeText(text);
        this.$message.success("复制成功")
      } catch (err) {
        this.$message.success("复制失败")
      }
    },
    rowFy(row , index){
      if(!util.isVoid(row.storyboard)){
        row.isLoad = true
        this.fyRequest(row , index).then(res=>{
          if(res.success === true){
            row.storyboarden = res.translated_text.toString()
          }
          row.isLoad = false
        })
      }

    },
    fyRequest(row , index){
      return http.post("/SD/physton_prompt/translates",{
        api : "baidu_free" ,
        api_config: {index} ,
        from_lang: "zh_CN" ,
        to_lang :  "en_US" ,
        texts : row.storyboard.split(/[\,\，]/)
      })
    },
    aiPrompt(row,index){

    },
    toTsc(){
      this.data.forEach(item=>{
        item.storyboard = item.text
      })
    },
    buildPrompt(){
      let storyboard = this.data.filter(item=>!util.isVoid(item.storyboard)).map(item=>{
        return `--prompt "${this.config.prompt},${item.storyboard}" --negative_prompt "${this.config.negativePrompt}"`
      }) ;
      let storyboarden = this.data.filter(item=>!util.isVoid(item.storyboarden)).map(item=>{
        let text = item.storyboarden.replace(/，/g,",").split("\n").filter(t=>!util.isVoid(t)).join(",")
        return `--prompt "${this.config.prompt},${text}" --negative_prompt "${this.config.negativePrompt}"`
      }) ;
      this.storyboardzh = storyboard.join("\n")
      this.storyboarden = storyboarden.join("\n")
      this.pStatus = true ;
    },
    deleteRow(index , state,dir){
      if(state){
        if(dir === "up"){
          this.data = this.data.slice(index, this.data.length-1)
        }else{
          this.data = this.data.slice(0, index+1)
        }
      }else{
        this.data.splice(index, 1)
      }
    },
    insertRow(index ){
      this.data.splice(index+1, 0, {text: '',storyboard:""}) // 替换上一行的内容
    },
    upMerge(index , row){//向上合并
      let item = this.data[index-1] //上一行数据
      item.text = `${item.text}，${row.text}`;
      if(!(commons.isVoid(item.storyboard) && commons.isVoid(row.storyboard))){
        item.storyboard = `${item.storyboard}，${row.storyboard}`
      }else{
        item.storyboard = util.ifTruthy(commons.isEmpty(row.storyboard),item.storyboard , `${item.storyboard}，${row.storyboard}`)
      }
      this.data.splice(index-1, index, item) // 替换上一行的内容
      this.data.splice(index, 1)
    },
    downMerge(index , row){//向下合并
      let item = this.data[index+1] // 下一行数据
      row.text = `${row.text}，${item.text}`;
      if(!(commons.isVoid(item.storyboard) && commons.isVoid(row.storyboard))){
        row.storyboard = `${row.storyboard}，${item.storyboard}`
      }else{
        row.storyboard = util.ifTruthy(commons.isEmpty(item.storyboard),row.storyboard , `${row.storyboard}，${item.storyboard}`)
      }
      this.data.splice(index, 1, row)
      this.data.splice(index+1, 1)
    }
  },
  watch:{
    dataList(){
      this.data = this.dataList.map(s=>{
        return {
          text: s,
          storyboard: "" ,
          storyboarden:"",
          isLoad: false
        }
      })
    }
  }
}
</script>

<style scoped>

</style>